import React from 'react';
import { inject, observer } from 'mobx-react';
import { Route, withRouter } from 'react-router-dom';
import { Icon, InputItem, List, Popover, SearchBar, Tabs, Tools, Modal,Bubble } from 'weaver-mobile';
import { ListViewPage,RouteLayout } from 'weaver-mobile-page';
import Condition from "./condition";
import { openHrmCard } from "../../../util";
import { toJS } from 'mobx';
import { WrListCard, WrListCardOperate, WrMenu, WrPicker } from "../../../public";
import { menuData } from '../coms'

const getLabel = Tools.getLabel;
const FormItem = List.FormItem;
const Item = Popover.Item;

/**
 * 考核评分
 */
@inject('planAuditStore')
@withRouter
@observer
export default class Index extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            visible: false, //右上角操作按钮
            show: false, //批量操作
            chooseAll: false //是否全选状态
        };
        this.store = this.props.planAuditStore;
    }
    componentWillMount() {
        if (window.refreshPlanAuditNum && typeof window.refreshPlanAuditNum === "function") {
            window.refreshPlanAuditNum();
        }
    }
    componentDidMount() {
        this.store.doInit();
    }

    render() {
        const { list, getTableDatas, tabs, onSearchChange, queryParams } = this.store;
        return (
            <div className="workrelate-performance-accessAudit workrelate-listCard-reset">
                {this.getHeader()}
                {/* <Tabs tabs={tabs}
                      initialPage={queryParams.showtype - 1}
                      onChange={(tab, index) => {
                          onSearchChange({'showtype': (index + 1)})
                          getTableDatas();
                      }}
                /> */}
                {this.state.show && this.getChoose()}
                <ListViewPage.Normal
                    store={list}
                    heightSpace={49}
                    showCheck={this.state.show}
                    getTemplate={this.getTemplate}
                    renderSeparator={this.renderSeparator}
                    onRowClick={data => this.getRowClick(data)}
                />
                {this.getBatchButton()}
                <Route
                    key="userCenter-myFans"
                    path="/planHome/planAudit/condition"
                    breadcrumbName="报告审批-高级搜索条件"
                    render={() => (
                        <RouteLayout>
                            <Condition />
                        </RouteLayout>
                    )}
                />
            </div>
        )
    }

    //获取批量操作
    getChoose = () => {
        const { list } = this.store;
        const { show, chooseAll } = this.state;
        let chooseNum = list.selectedRowKeys.length;
        return (
            <div className="accessAudit-batch-choose">
                <span onClick={() => {
                    list.selectNone();
                    this.setState({
                        show: false,
                    })
                }}>{getLabel(31129, "取消")}</span>
                <span>{getLabel(513668, "已选择{num}条数据").replace("{num}", chooseNum)}</span>
                <span style={{ color: chooseAll && "#55B1F9" }} onClick={() => {
                    if (chooseAll) {
                        list.selectNone();
                    } else {
                        list.selectAll();
                    }
                    this.setState({ chooseAll: !chooseAll })
                }}>{getLabel(556, "全选")}</span>
            </div>
        )
    }

    //获取批量操作
    getBatchButton = () => {
        const { list } = this.store;
        return (
            this.state.show ?
                <div className="accessAudit-batch-button">
                    <span className='item-batch-detail' onClick={() => {
                        this.auditBatch({
                            planIds: list.selectedRowKeys,
                            operation: 'quick_approve'
                        }, getLabel('509442', '确认批准吗？'))
                    }}>
                        <span><Icon type="approval" /></span>
                        <span className="desc">{getLabel(83212, "批量批准")}</span>
                    </span>
                    <span className='item-batch-detail' onClick={() => {
                        this.auditBatch({
                            planIds: list.selectedRowKeys,
                            operation: 'quick_return'
                        }, getLabel('509443', '确认退回吗？'))
                    }}>
                        <span><Icon type="end" /></span>
                        <span className="desc">{getLabel(83423, "批量退回")}</span>
                    </span>
                </div> : <WrMenu
                _width={'60px'}
                    data={this.props.menuData}
                    onSelect={val => this.props.history.push(val.props.path)}
                // buttonData={this.buildOperateButton()}
                />

        )
    }

    //行点击事件
    getRowClick = (data) => {
        const { list } = this.store;
        const { show } = this.state;
        if (show) {
            //修改选中框值
            if (list.selectedRowKeys.includes(data.id)) {
                list.selectedRowKeys = list.selectedRowKeys.filter(n => n != data.id)
            } else {
                list.selectedRowKeys.push(data.id + '')
            }
        } else {
            this.props.history.push({
                pathname: '/planHome/planView/index',
                search: 'planid=' + data.id
            })
        }
    }

    //每列数据操作按钮
    renderSeparator = (section, index) => {
        const { list, queryParams } = this.store;
        const data = toJS(list.data)[index];
        const params = [{
            label: getLabel(142, '批准'),
            iconname: 'approval',
            onClick: () => this.auditSingle({
                planid: data.id,
                operation: 'approve',
            }, getLabel('509442', '确认批准吗？'))
        }, {
            label: getLabel(236, '退回'),
            iconname: 'end',
            onClick: () => this.auditSingle({
                planid: data.id,
                operation: 'return',
            }, getLabel('509443', '确认退回吗？'))
        }]
        return <WrListCardOperate
            showOperate={queryParams.showtype != 1 && !this.state.show}
            showSpace={index != list.data.length - 1}
            data={params} />;
    }

    //单个审核
    auditSingle = (params, message) => {
        Modal.alert(message, '', [
            { text: getLabel(31129, '取消') },
            {
                text: getLabel(826, '确定'),
                onPress: () => this.store.auditSingle(params)
            },
        ])
    }

    //批量审核
    auditBatch = (params, message) => {
        if(!params.planIds || params.planIds.length<1){
            Bubble.warning(getLabel(501159, "请选择要操作的数据"))
            return 
        }
        Modal.alert(message, '', [
            { text: getLabel(31129, '取消') },
            {
                text: getLabel(826, '确定'),
                onPress: () => this.store.auditBatch(params)
            },
        ])
    }

    //审核数据
    auditData = (params, message) => {
        Modal.alert(message, '', [
            { text: getLabel(31129, '取消') },
            {
                text: getLabel(826, '确定'),
                onPress: () => this.store.accessAuditOperation(params)
            },
        ])
    }

    //获取表头
    getHeader = () => {
        const { search, queryParams, onSearchChange, getTableDatas } = this.store;
        return (
            <SearchBar
                value={queryParams.searchTitleValue}
                placeholder={getLabel(500351, '请输入关键字')}
                showExtraButton
                extraButton={this.getExtraButton()}
                onChange={val => onSearchChange({ 'searchTitleValue': val })}
                onSubmit={getTableDatas}
                onSelectButtonClick={() => {
                }}
            />
        )
    }

    //获取搜索框额外按钮
    getExtraButton = () => {
        const { search, queryParams } = this.store;
        let button = [{
            key: 'filter',
            show: <span onClick={() => this.props.history.push('/planHome/planAudit/condition')}>
                <Icon key='filter-o' type='filter-o' />
            </span>
        }]
        queryParams.showtype != 1 && button.push({
            key: 'operate',
            show: <Popover
                mask
                visible={this.state.visible}
                onSelect={this.onPopoverSelect}
                overlay={[
                    ((<div className="workrelate-header-item">
                        <Popover.Item><span
                            className="workrelate-header-item-cycle">{getLabel(500410, "批量操作")}</span></Popover.Item>
                    </div>
                    )),

                ]}
            >
                <Icon key='ellipsis' type='ellipsis' />
            </Popover>
        })
        return button;
    }

    //右上角按钮触发
    onPopoverSelect = (node, index) => {
        this.setState({ show: true })
    }

    //获取数据模板
    getTemplate = (template) => {
        return {
            default: [{
                render: data => <WrListCard data={[
                    { label: getLabel('24986', '标题'), value: data.planname },
                    // {label: '周期', value: data.yearspan},
                    {
                        label: getLabel('30042', '人员'), value: (<a href='javaScript:void(0)' onClick={(e) => openHrmCard(data.userid, e)}>
                            {data.useridspan}
                        </a>)
                    },
                    { label: getLabel(33553, '分部'), value: data.subcompanyid1span },
                    { label: getLabel(27511, '部门'), value: data.departmentidspan },
                    { label: getLabel('22326', '截止时间：'), value: data.enddate },
                ]} />
            }]
        }
    }

}

